
package cn.javaxc.mvcwork.controller;
import cn.javaxc.mvcwork.controller.*;
import cn.javaxc.mvcwork.framework.actions.TActionContext;
import cn.javaxc.mvcwork.framework.database.*;
import cn.javaxc.mvcwork.util.common.DatabaseUtils;
import java.sql.*;





public class AuthenticationItem {
  //HTTP-XML API Authentication Header Types
  public final static int ASPMODE = 1;
  public final static int SYNC_CLIENT = 2;
  public final static int CENTRIC_USER = 3;
  public final static int SYNC_CLIENT_USER_BASED = 4;

  private String id = null;
  private String code = null;
  private int systemId = -1;
  private int clientId = -1;
  private java.sql.Timestamp lastAnchor = null;
  private java.sql.Timestamp nextAnchor = null;
  private String authCode = "unset";
  private String encoding = "UTF-8";
  private String username = null;
  private String url = null;


  
  public AuthenticationItem() { }


  
  public String getUrl() {
    return url;
  }


  
  public void setUrl(String tmp) {
    this.url = tmp;
  }


  
  public void setId(String tmp) {
    id = tmp;
  }


  
  public void setCode(String tmp) {
    code = tmp;
  }


  
  public void setClientId(int tmp) {
    clientId = tmp;
  }


  
  public void setClientId(String tmp) {
    clientId = Integer.parseInt(tmp);
  }


  
  public void setSystemId(int tmp) {
    this.systemId = tmp;
  }


  
  public void setSystemId(String tmp) {
    this.systemId = Integer.parseInt(tmp);
  }




  
  public void setAuthCode(String tmp) {
    this.authCode = tmp;
  }


  
  public void setEncoding(String tmp) {
    this.encoding = tmp;
  }


  
  public String getUsername() {
    return username;
  }


  
  public void setUsername(String tmp) {
    this.username = tmp;
  }


  
  public String getId() {
    return id;
  }


  
  public String getCode() {
    return code;
  }


  
  public int getClientId() {
    return clientId;
  }


  
  public int getSystemId() {
    return systemId;
  }


  
  public java.sql.Timestamp getLastAnchor() {
    return lastAnchor;
  }


  
  public void setLastAnchor(java.sql.Timestamp tmp) {
    this.lastAnchor = tmp;
  }


  
  public void setLastAnchor(String tmp) {
    this.lastAnchor = DatabaseUtils.parseTimestamp(tmp);
  }


  
  public java.sql.Timestamp getNextAnchor() {
    return nextAnchor;
  }


  
  public void setNextAnchor(java.sql.Timestamp tmp) {
    this.nextAnchor = tmp;
  }


  
  public void setNextAnchor(String tmp) {
    this.nextAnchor = DatabaseUtils.parseTimestamp(tmp);
  }



  
  public String getAuthCode() {
    return authCode;
  }


  
  public String getEncoding() {
    return encoding;
  }


  
  public int getType() {
    if (username != null && clientId > -1 && code != null) {
      return AuthenticationItem.SYNC_CLIENT_USER_BASED;
    }
    if (username != null && clientId > -1) {
      return -1;//can't determine if it is a user or a sync client
    }
    if (username != null) {
      return AuthenticationItem.CENTRIC_USER;
    }
    if (clientId > -1) {
      return AuthenticationItem.SYNC_CLIENT;
    }

    return -1;
  }


  
  public Connection getConnection(TActionContext context) throws SQLException {
    return getConnection(context, true);
  }


  
  public ConnectionElement getConnectionElement(TActionContext context) throws SQLException {
    MVCConfig prefs = (MVCConfig) context.getServletContext().getAttribute("mvc");
    //Query the gatekeeper for the connectionElement info
    String gkHost = prefs.get("gatekeeper.url");
    String gkUser = prefs.get("gatekeeper.user");
    String gkUserPw = prefs.get("gatekeeper.password");
    String siteCode = prefs.get(MVCConstant.DB_CODE);
    String gkDriver = prefs.get("gatekeeper.driver");
    String serverName = context.getRequest().getServerName();
    if (System.getProperty("DEBUG") != null) {
      System.out.println("AuthenticationItem-> GateKeeper: " + gkHost);
      System.out.println("AuthenticationItem-> ServerName: " + serverName);
      System.out.println("AuthenticationItem-> SiteCode: " + siteCode);
      System.out.println("AuthenticationItem-> Driver: " + gkDriver);
    }
    ConnectionPool sqlDriver = (ConnectionPool) context.getServletContext().getAttribute(
        "ConnectionPool");
    ConnectionElement gk = new ConnectionElement(gkHost, gkUser, gkUserPw);
    gk.setDriver(gkDriver);
    if (!MVCConfig.getConfig().isSiteMode()) {
      // This system is not configured with the sites table, must be a binary version
      gk.setDbName(prefs.get("gatekeeper.database"));
      if (System.getProperty("DEBUG") != null) {
        System.out.println("AuthenticationItem-> Database: " + gk.getDbName());
      }
      return gk;
    }
    Connection db = null;
    try {
      ConnectionElement ce = null;
      db = sqlDriver.getConnection(gk);
      PreparedStatement pst = db.prepareStatement(
          "SELECT * " +
          "FROM ts_sites " +
          "WHERE sitecode = ? " +
          "AND vhost = ? ");
      pst.setString(1, siteCode);
      pst.setString(2, serverName);
      ResultSet rs = pst.executeQuery();
      if (rs.next()) {
        String siteDbHost = rs.getString("dbhost");
        String siteDbName = rs.getString("dbname");
        String siteDbUser = rs.getString("dbuser");
        String siteDbPw = rs.getString("dbpw");
        String siteDriver = rs.getString("driver");
        authCode = rs.getString("code");
        ce = new ConnectionElement(siteDbHost, siteDbUser, siteDbPw);
        ce.setDbName(siteDbName);
        ce.setDriver(siteDriver);
      }
      rs.close();
      pst.close();
      return ce;
    } catch (Exception e) {
      throw new SQLException(e.getMessage());
    } finally {
      if (db != null) {
        sqlDriver.free(db);
      }
    }
  }


  
  public Connection getConnection(TActionContext context, boolean checkCode) throws SQLException {
    ConnectionElement ce = this.getConnectionElement(context);
    if (this.isAuthenticated(context, checkCode)) {
      if (ce != null) {
        ConnectionPool sqlDriver = (ConnectionPool) context.getServletContext().getAttribute(
            "ConnectionPool");
        return sqlDriver.getConnection(ce);
      }
    }
    return null;
  }


  
  public boolean isAuthenticated(TActionContext context) {
    return this.isAuthenticated(context, true);
  }


  
  public boolean isAuthenticated(TActionContext context, boolean checkCode) {
    String serverName = context.getRequest().getServerName();
    if (!checkCode) {
      return true;
    }
    if (id != null && id.equals(serverName)) {
      if (code != null && authCode != null && code.equals(authCode)) {
        return true;
      }
    }
    return false;
  }
}
